package club.blueline.articleapi.controller;

import club.blueline.articleapi.entity.CategoryInfoDo;
import club.blueline.articleapi.entity.Result;
import club.blueline.articleapi.entity.ResultCode;
import club.blueline.articleapi.mapper.CategoryMapper;
import club.blueline.articleapi.utils.ResultUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/category")
public class CategoryController {

    @Resource
    private CategoryMapper categoryMapper;

    @GetMapping
    public Result getCategoryList() {
        List<CategoryInfoDo> list = categoryMapper.getAll();
        if(list == null) {
            Result result = ResultUtils.genFailResult("获取分类失败！");
            result.setCode(ResultCode.FAIL.code());
            return result;
        }
        return ResultUtils.genSuccessResult(list);
    }

    @PostMapping
    public Result addCategory(@RequestBody String name) {
        if(categoryMapper.addCategory(name) != 1) {
            Result result = ResultUtils.genFailResult("添加分类失败！");
            result.setCode(ResultCode.FAIL.code());
            return result;
        }
        return ResultUtils.genSuccessResult();
    }

    @PutMapping
    public Result editCategory(@RequestBody CategoryInfoDo categoryInfo) {
        if(categoryMapper.editCategory(categoryInfo) != 1) {
            Result result = ResultUtils.genFailResult("修改分类失败！");
            result.setCode(ResultCode.FAIL.code());
            return result;
        }
        return ResultUtils.genSuccessResult();
    }

    @DeleteMapping
    public Result deleteCategory(@RequestParam(value = "id") Integer id) {
        if(categoryMapper.deleteCategory(id) != 1) {
            Result result = ResultUtils.genFailResult("删除分类失败！");
            result.setCode(ResultCode.FAIL.code());
            return result;
        }
        return ResultUtils.genSuccessResult();
    }

}
